<template>
  <div class="block-list-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchParams" inline>
        <el-form-item label="封禁ID">
          <el-input
            v-model="searchParams.content"
            placeholder="请输入设备ID或IP地址"
            clearable
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label="封禁类型">
          <el-select
            v-model="searchParams.type"
            placeholder="请选择封禁类型"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="(text, value) in blockTypes"
              :key="value"
              :label="text"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 400px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>封禁记录列表</span>
        </div>
      </template>

      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        stripe
        table-layout="auto"
      >
        <el-table-column prop="userNo" label="用户编号" min-width="100" />
        <el-table-column prop="nickname" label="用户昵称" min-width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar
                :size="32"
                :src="row.avatar"
                @click="handlePreviewAvatar(row.avatar, row.nickname)"
                class="clickable-avatar"
              />
              <span class="nickname">{{ row.nickname }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="content"
          label="封禁ID"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column prop="type" label="封禁类型" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getBlockTypeTagType(row.type)">
              {{ blockTypes[row.type] || `类型${row.type}` }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reasonCategory" label="封禁原因" min-width="100">
          <template #default="{ row }">
            <el-tag type="danger" size="small">
              {{ getBlockCategoryText(row.reasonCategory) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ row.remark || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" min-width="140">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" min-width="140">
          <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="BlockStatusType[row.status]">
              {{ BlockStatusText[row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operatorUserId" label="操作人" min-width="100" />
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="140"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="80" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                v-if="row.status === BlockStatus.YES"
                type="success"
                size="default"
                @click="handleUnblock(row)"
              >
                <el-icon><Unlock /></el-icon>
                解封
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totals"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Unlock } from "@element-plus/icons-vue";
import {
  getBlockPageApi,
  getBlockTypesApi,
  getBlockCategoriesApi,
  unBlockApi,
  BlockSearchReq,
  BlockRecordDto,
  BlockTypeText,
  BlockTypeType,
  ReasonCategoryText,
  BlockStatusText,
  BlockStatusType,
  BlockStatus,
  BlockTypesRes,
  BlockCategoriesRes,
} from "@/api/block";

// 响应式数据
const loading = ref(false);
const tableData = ref<BlockRecordDto[]>([]);
const totals = ref(0);
const dateRange = ref<[string, string] | null>(null);
const blockTypes = ref<BlockTypesRes>({});
const blockCategories = ref<BlockCategoriesRes>({});

// 搜索参数
const searchParams = reactive<BlockSearchReq>({
  content: "",
  type: undefined,
  startTime: "",
  endTime: "",
  pageIndex: 1,
  pageSize: 10,
});

// 分页参数
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
});

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    // 处理时间范围
    if (dateRange.value) {
      searchParams.startTime = convertToUTC(dateRange.value[0]);
      searchParams.endTime = convertToUTC(dateRange.value[1]);
    } else {
      searchParams.startTime = "";
      searchParams.endTime = "";
    }

    const response = await getBlockPageApi(searchParams);
    tableData.value = response.data.list;
    totals.value = response.data.total;
  } catch (error) {
    console.error("加载封禁记录失败:", error);
    ElMessage.error("加载数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  searchParams.pageIndex = 1;
  pagination.pageIndex = 1;
  loadData();
};

// 重置
const handleReset = () => {
  searchParams.content = "";
  searchParams.type = undefined;
  dateRange.value = null;
  searchParams.startTime = "";
  searchParams.endTime = "";
  searchParams.pageIndex = 1;
  pagination.pageIndex = 1;
  loadData();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  searchParams.pageSize = size;
  pagination.pageSize = size;
  searchParams.pageIndex = 1;
  pagination.pageIndex = 1;
  loadData();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  searchParams.pageIndex = page;
  pagination.pageIndex = page;
  loadData();
};

// 解封
const handleUnblock = async (row: BlockRecordDto) => {
  try {
    await ElMessageBox.confirm(
      `确定要解封用户 ${row.nickname} 的${
        blockTypes.value[row.type] || `类型${row.type}`
      }吗？`,
      "确认解封",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 调用解封接口
    await unBlockApi(row.id);
    ElMessage.success("解封成功");

    // 刷新列表
    loadData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("解封失败:", error);
      ElMessage.error("解封失败");
    }
  }
};

// 预览头像
const handlePreviewAvatar = (avatarUrl: string, nickname: string) => {
  if (!avatarUrl) {
    ElMessage.warning("暂无头像");
    return;
  }

  // 使用 Element Plus 的图片预览功能
  const h = ElMessageBox.alert;
  ElMessageBox.alert(
    `<div style="text-align: center;">
      <img src="${avatarUrl}" style="max-width: 100%; max-height: 400px; border-radius: 8px;" />
      <p style="margin-top: 10px; font-size: 16px; color: #666;">${nickname} 的头像</p>
    </div>`,
    "头像预览",
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: "关闭",
      customClass: "avatar-preview-dialog",
    }
  );
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "-";
  // 检查是否为永久封禁时间
  if (dateTime?.startsWith("9999-")) return "永久封禁";
  const date = new Date(dateTime);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 转换为UTC时间
const convertToUTC = (localTime: string) => {
  if (!localTime) return "";
  const date = new Date(localTime);
  return date.toISOString();
};

// 获取封禁类型标签样式
const getBlockTypeTagType = (type: number) => {
  const typeMap: Record<number, string> = {
    1: "danger", // 账号封禁
    2: "warning", // 设备封禁
    3: "info", // IP封禁
    4: "warning", // 限制登录类型
  };
  return typeMap[type] || "info";
};

// 获取封禁原因文本
const getBlockCategoryText = (category: string) => {
  const categoryData = blockCategories.value[category];
  if (categoryData) {
    return categoryData.zh; // 返回中文名称
  }
  return category || "未知原因";
};

// 加载封禁类型
const loadBlockTypes = async () => {
  try {
    const response = await getBlockTypesApi();
    blockTypes.value = response.data;
  } catch (error) {
    console.error("加载封禁类型失败:", error);
    ElMessage.error("加载封禁类型失败");
  }
};

// 加载封禁原因分类
const loadBlockCategories = async () => {
  try {
    const response = await getBlockCategoriesApi();
    blockCategories.value = response.data;
  } catch (error) {
    console.error("加载封禁原因分类失败:", error);
    ElMessage.error("加载封禁原因分类失败");
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadBlockTypes();
  loadBlockCategories();
  loadData();
});
</script>

<style scoped lang="less">
.block-list-container {
  padding: 20px;
  font-size: 16px; // 整体字号调整
  width: 100%;
  max-width: 100%;
  overflow-x: auto; // 添加横向滚动

  .search-card {
    margin-bottom: 20px;

    :deep(.el-form-item__label) {
      font-size: 16px;
      font-weight: 500;
    }

    :deep(.el-input__inner) {
      font-size: 16px;
    }

    :deep(.el-select .el-input__inner) {
      font-size: 16px;
    }

    :deep(.el-button) {
      font-size: 16px;
      padding: 12px 20px;
    }
  }

  .table-card {
    width: 100%;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 18px;
      font-weight: 600;

      .header-actions {
        display: flex;
        gap: 10px;

        .el-button {
          font-size: 16px;
          padding: 12px 20px;
        }
      }
    }

    :deep(.el-table) {
      font-size: 16px;
      width: 100% !important;
      min-width: 1070px; // 设置最小宽度，确保所有列都能显示

      .el-table__header {
        th {
          font-size: 16px;
          font-weight: 600;
          padding: 16px 8px;
        }
      }

      .el-table__body {
        td {
          font-size: 16px;
          padding: 16px 8px;
        }
      }

      .el-table__inner-wrapper {
        width: 100% !important;
      }

      .el-table__body-wrapper {
        width: 100% !important;
      }
    }

    :deep(.el-tag) {
      font-size: 14px;
      padding: 6px 12px;
    }
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 6px;

    .clickable-avatar {
      cursor: pointer;
      transition: transform 0.2s ease;
      flex-shrink: 0;

      &:hover {
        transform: scale(1.1);
      }
    }

    .nickname {
      font-weight: 500;
      font-size: 16px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .action-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
    justify-content: flex-start;
    flex-wrap: wrap;

    .el-button {
      margin: 0;
      flex-shrink: 0;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;

    :deep(.el-pagination) {
      font-size: 16px;

      .el-pagination__total {
        font-size: 16px;
      }

      .el-pagination__sizes {
        .el-select .el-input__inner {
          font-size: 16px;
        }
      }

      .btn-prev,
      .btn-next {
        font-size: 16px;
      }

      .el-pager li {
        font-size: 16px;
      }
    }
  }
}

// 全局样式，用于头像预览对话框
:global(.avatar-preview-dialog) {
  .el-message-box__content {
    padding: 20px;
  }

  .el-message-box__message {
    margin: 0;
  }
}
</style>
